package com.yaowk.sfp.security;

import com.yaowk.sfp.security.api.model.User;
import com.yaowk.sfp.security.utils.ISecurityUtils;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

@Component
public class SecurityUtils implements ISecurityUtils {
    @Override
    public User getUser() {
        Object object = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (!ObjectUtils.isEmpty(object) && object instanceof UserInfo) {
            UserInfo userInfo = (UserInfo) object;
            User user = new User();
            user.setId(userInfo.getId());
            user.setUsername(userInfo.getUsername());
            return user;
        }
        throw new AccessDeniedException("请登录后重试！");
    }

    @Override
    public Long getUserId() {
        User userInfo = getUser();
        if (!ObjectUtils.isEmpty(userInfo)) {
            return userInfo.getId();
        }
        return null;
    }
}
